import time
import hashlib
import hmac
import requests
# 您的API凭证（从币安官方获取）
# api_key = "oMlYVBgANplqH7XilK0rzJ47r7p1R3MWoywVNBYOGvj5UHYXebQnxZjX9kLpdd5V"
# secret_key = "8587vRjV45QsPPXhlrn3vcBdUwQJFA6HIBqfaVbJO7UqhhqTcVrQCR4GEO6w4OtN"
API_KEY = "oMlYVBgANplqH7XilK0rzJ47r7p1R3MWoywVNBYOGvj5UHYXebQnxZjX9kLpdd5V"
API_SECRET = "8587vRjV45QsPPXhlrn3vcBdUwQJFA6HIBqfaVbJO7UqhhqTcVrQCR4GEO6w4OtN"

# 币安API基础URL
BASE_URL = "https://api.binance.com"

def get_timestamp():
    """获取当前时间戳"""
    return int(time.time() * 1000)

def get_binance_server_time():
    url = "https://api.binance.com/api/v3/time"
    response = requests.get(url)
    if response.status_code == 200:
        server_time = response.json()['serverTime']
        return server_time
    else:
        raise Exception("无法获取币安服务器时间")


def get_adjusted_timestamp(time_diff):
    return int(time.time() * 1000) + time_diff


def create_signature(query_string):
    """创建HMAC SHA256签名"""
    return hmac.new(
        API_SECRET.encode('utf-8'),
        query_string.encode('utf-8'),
        hashlib.sha256
    ).hexdigest()


def get_account_balance():
    """获取账户余额"""
    endpoint = "/api/v3/account"

    # 计算本地时间与服务器时间的差值（毫秒）
    local_time_ms = int(time.time() * 1000)
    server_time_ms = get_binance_server_time()
    time_diff = server_time_ms - local_time_ms

    # timestamp = get_timestamp()
    timestamp = get_adjusted_timestamp(time_diff)
    params = f"timestamp={timestamp}"
    signature = create_signature(params)

    headers = {"X-MBX-APIKEY": API_KEY}
    url = f"{BASE_URL}{endpoint}?{params}&signature={signature}"

    response = requests.get(url, headers=headers)

    if response.status_code == 200:
        data = response.json()
        balances = [asset for asset in data['balances'] if float(asset['free']) > 0 or float(asset['locked']) > 0]
        return balances
    else:
        print(f"错误: {response.status_code}")
        return None


# 使用示例
balances = get_account_balance()
if balances:
    for balance in balances:
        print(f"{balance['asset']}: 可用={balance['free']}, 锁定={balance['locked']}")